package com.ysd.gulimall.order.service.impl;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import feign.FeignException;
import com.ysd.common.utils.R;
import com.ysd.common.vo.MemberRespVo;
import com.ysd.gulimall.order.entity.OrderItemEntity;
import com.ysd.gulimall.order.enume.OrderStatusEnum;
import com.ysd.gulimall.order.feign.CartFeignService;
import com.ysd.gulimall.order.feign.MemberFeignService;
import com.ysd.gulimall.order.feign.ProductFeignService;
import com.ysd.gulimall.order.feign.WmsFeignService;
import com.ysd.gulimall.order.interceptor.LoginUserInterceptor;
import com.ysd.gulimall.order.service.OrderItemService;
import com.ysd.gulimall.order.to.OrderCreateTo;
import com.ysd.gulimall.order.to.SpuInfoVo;
import com.ysd.gulimall.order.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysd.common.utils.PageUtils;
import com.ysd.common.utils.Query;

import com.ysd.gulimall.order.dao.OrderDao;
import com.ysd.gulimall.order.entity.OrderEntity;
import com.ysd.gulimall.order.service.OrderService;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.springframework.util.StringUtils;
import com.alibaba.fastjson.TypeReference;

import javax.servlet.http.HttpSession;

@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal = new ThreadLocal<>();
    private Long mids=null;
    MemberAddressVo address = null;//
    @Autowired
    MemberFeignService memberFeignService;
//    @Autowired
//    private WmsFeignService wmsFeignService;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    CartFeignService cartFeignService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }
//    @Retryable(value ={FeignException.class},maxAttempts = 3,backoff = @Backoff(delay = 2l,multiplier = 1))
    public    List<MemberAddressVo> setAddress(Long mid,int i) throws InterruptedException {
        List<MemberAddressVo> ls=null;
        try {
              ls=memberFeignService.getAddress(mid);
              for (MemberAddressVo mv:ls){
                  System.out.println(mv.getId());
                  System.out.println(mids);
                if(mv.getId().equals(mids)){
                    address=mv;
                }
              }
        }catch (Exception e){
            if(i<=5){
                Thread.sleep(3000);
                int j=i+1;
                System.out.println("第"+(j-1)+"次重试address！");
                setAddress(mid,j);

            }else{
                e.printStackTrace();
            }
        }

        return ls;
    }
//    @Retryable(value ={FeignException.class},maxAttempts = 3,backoff = @Backoff(delay = 2l,multiplier = 1))
    public  R setSpuInfo(Long skuId,int i) throws InterruptedException {
        R r=null;
        try {

            r=productFeignService.getSpuInfoBySkuId(skuId);
        }catch (Exception e){
            if(i<=5){
                Thread.sleep(3000);
                int j=i+1;
                System.out.println("第"+(j-1)+"次重试,pro！");
                setSpuInfo(skuId,j);

            }else{
                e.printStackTrace();
            }
        }
        return r;
    }
    @Override
    public OrderConfirmVo confirmOrder() throws InterruptedException {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        //拦截器获取用
        MemberRespVo member = LoginUserInterceptor.loginUser.get();

        List<MemberAddressVo> address = setAddress(member.getId(),1);
        orderConfirmVo.setMemberAddressVos(address);
        //获取选中的购物项
        List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
        orderConfirmVo.setItems(currentUserCartItems);
        

        //存储商品库存信息
        Map m=new HashMap<Long,Boolean>();
        m.put(1L,true);
        orderConfirmVo.setStocks(m);

        return orderConfirmVo;
    }
    private void saveOrder(OrderCreateTo orderCreateTo) {

        //获取订单信息
        OrderEntity order = orderCreateTo.getOrder();
        order.setModifyTime(new Date());
        order.setCreateTime(new Date());
        //保存订单
        this.baseMapper.insert(order);

        //获取订单项信息
        List<OrderItemEntity> orderItems = orderCreateTo.getOrderItems();
        //批量保存订单项数据
        orderItemService.saveBatch(orderItems);
    }
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        confirmVoThreadLocal.set(vo);
        mids=vo.getAddrId();
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        //去创建、下订单、验令牌、验价格、锁定库存...
        OrderCreateTo order = createOrder();



        saveOrder(order);
        responseVo.setCode(0);
        responseVo.setOrder(order.getOrder());
        return responseVo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id",memberRespVo.getId()).orderByDesc("id")
        );
        List<OrderEntity> order_sn = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(itemEntities);
            return order;
        }).collect(Collectors.toList());
        page.setRecords(order_sn);
        return new PageUtils(page);
    }

    private OrderCreateTo createOrder() {

        OrderCreateTo createTo = new OrderCreateTo();

        //1、生成订单号
        String orderSn = IdWorker.getTimeId().substring(0,16);
        OrderEntity orderEntity = builderOrder(orderSn);

        //2、获取到所有的订单项
        List<OrderItemEntity> orderItemEntities = builderOrderItems(orderSn);

        //3、验价(计算价格、积分等信息)
        computePrice(orderEntity,orderItemEntities);

        createTo.setOrder(orderEntity);
        createTo.setOrderItems(orderItemEntities);

        return createTo;
    }
    private OrderEntity builderOrder(String orderSn) {

        //获取当前用户登录信息
        MemberRespVo memberResponseVo = LoginUserInterceptor.loginUser.get();

        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setMemberId(memberResponseVo.getId());
        //orderEntity.setMemberId(1L);
        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberUsername(memberResponseVo.getUsername());
       // orderEntity.setMemberUsername("admin");

        OrderSubmitVo orderSubmitVo = confirmVoThreadLocal.get();

//        R fareAddressVo = wmsFeignService.getFare(orderSubmitVo.getAddrId());
//        FareVo fareResp = fareAddressVo.getData("data", new TypeReference<FareVo>() {});

        //获取到运费信息
//        BigDecimal fare = fareResp.getFare();
        orderEntity.setFreightAmount(BigDecimal.valueOf(10));

        //获取到收货地址信息
//        MemberAddressVo address = fareResp.getAddress();
        //TODO 设置收货人信息
        orderEntity.setReceiverName(memberResponseVo.getNickname());
        orderEntity.setReceiverPhone(memberResponseVo.getMobile());

        //confirmVoThreadLocal
        if(address!=null){
            orderEntity.setReceiverPostCode(address.getPostCode());
            orderEntity.setReceiverProvince(address.getProvince());
            orderEntity.setReceiverCity(address.getCity());
            orderEntity.setReceiverRegion(address.getRegion());
            orderEntity.setReceiverDetailAddress(address.getDetailAddress());
        }else{
            orderEntity.setReceiverPostCode("462000");
            orderEntity.setReceiverProvince("HeNan");
            orderEntity.setReceiverCity("ZhengZhou");
            orderEntity.setReceiverRegion("HuanYuanLu");
            orderEntity.setReceiverDetailAddress("136L");
        }


        //设置订单相关的状态信息
        orderEntity.setStatus(1);
        orderEntity.setAutoConfirmDay(7);
        orderEntity.setConfirmStatus(0);
        return orderEntity;
    }
    /**
     * 构建所有订单项数据
     * @return
     */
    public List<OrderItemEntity> builderOrderItems(String orderSn) {

        List<OrderItemEntity> orderItemEntityList = new ArrayList<>();

        //最后确定每个购物项的价格
        List<OrderItemVo> currentCartItems = cartFeignService.getCurrentUserCartItems();
        //添加购物项
       // List<OrderItemVo> currentCartItems = new ArrayList<OrderItemVo>();
      //  currentCartItems.add(new OrderItemVo(1L,true,"华为 HUAWEI Mate 30 Pro 星河银 8GB+256GB麒麟990旗舰芯片OLED环幕屏双4000万徕卡电影四摄4G全网通手机","https://gulimall-hello.oss-cn-beijing.aliyuncs.com/2019-11-26/60e65a44-f943-4ed5-87c8-8cf90f403018_d511faab82abb34b.jpg",new ArrayList<String>(), BigDecimal.valueOf(6299.0000),1,BigDecimal.valueOf(6299.0000),BigDecimal.valueOf(10)));
        if (currentCartItems != null && currentCartItems.size() > 0) {
            orderItemEntityList = currentCartItems.stream().map((items) -> {
                //构建订单项数据
                OrderItemEntity orderItemEntity = builderOrderItem(items);
                orderItemEntity.setOrderSn(orderSn);

                return orderItemEntity;
            }).collect(Collectors.toList());
        }

        return orderItemEntityList;
    }
    /**
     * 构建某一个订单项的数据
     * @param items
     * @return
     */
    private OrderItemEntity builderOrderItem(OrderItemVo items) {

        OrderItemEntity orderItemEntity = new OrderItemEntity();

        //1、商品的spu信息
        Long skuId = items.getSkuId();
        System.out.println("skuiddddddddddddddddddd"+skuId);
        //TODO 获取spu的信息
        try {
        R spuInfo= setSpuInfo(skuId,1);
//        R spuInfo = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo spuInfoData = spuInfo.getData("data", new TypeReference<SpuInfoVo>() {
        });
        orderItemEntity.setSpuId(spuInfoData.getId());
        orderItemEntity.setSpuName(spuInfoData.getSpuName());
        orderItemEntity.setSpuBrand(spuInfoData.getBrandId()+"");
        orderItemEntity.setCategoryId(spuInfoData.getCatalogId());
        System.out.println("name=============="+spuInfoData.getSpuName()+spuInfoData.getBrandId());
        //2、商品的sku信息
        orderItemEntity.setSkuId(skuId);
        orderItemEntity.setSkuName(items.getTitle());
        orderItemEntity.setSkuPic(items.getImage());
        orderItemEntity.setSkuPrice(items.getPrice());
        orderItemEntity.setSkuQuantity(items.getCount());
        System.out.println("price=============="+items.getPrice()+items.getTitle());
        //使用StringUtils.collectionToDelimitedString将list集合转换为String
        String skuAttrValues = StringUtils.collectionToDelimitedString(items.getSkuAttrValues(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttrValues);

        //3、商品的优惠信息

        //4、商品的积分信息
        orderItemEntity.setGiftGrowth(items.getPrice().multiply(new BigDecimal(items.getCount())).intValue());
        orderItemEntity.setGiftIntegration(items.getPrice().multiply(new BigDecimal(items.getCount())).intValue());

        //5、订单项的价格信息
        orderItemEntity.setPromotionAmount(BigDecimal.ZERO);
        orderItemEntity.setCouponAmount(BigDecimal.ZERO);
        orderItemEntity.setIntegrationAmount(BigDecimal.ZERO);

        //当前订单项的实际金额.总额 - 各种优惠价格
        //原来的价格
        BigDecimal origin = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        //原价减去优惠价得到最终的价格
        BigDecimal subtract = origin.subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(subtract);
        }catch (Exception e){

        }
        return orderItemEntity;
    }
    /**
     * 计算价格的方法
     * @param orderEntity
     * @param orderItemEntities
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {

        //总价
        BigDecimal total = new BigDecimal("0.0");
        //优惠价
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal intergration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");

        //积分、成长值
        Integer integrationTotal = 0;
        Integer growthTotal = 0;

        //订单总额，叠加每一个订单项的总额信息
        for (OrderItemEntity orderItem : orderItemEntities) {
            //优惠价格信息
            coupon = coupon.add(orderItem.getCouponAmount());
            promotion = promotion.add(orderItem.getPromotionAmount());
            intergration = intergration.add(orderItem.getIntegrationAmount());

            //总价
            total = total.add(orderItem.getRealAmount());

            //积分信息和成长值信息
            integrationTotal += orderItem.getGiftIntegration();
            growthTotal += orderItem.getGiftGrowth();

        }
        //1、订单价格相关的
        orderEntity.setTotalAmount(total);
        //设置应付总额(总额+运费)
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setCouponAmount(coupon);
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(intergration);

        //设置积分成长值信息
        orderEntity.setIntegration(integrationTotal);
        orderEntity.setGrowth(growthTotal);

        //设置删除状态(0-未删除，1-已删除)
        orderEntity.setDeleteStatus(0);

    }
}